#include<bits/stdc++.h>
#define ll long long
#define L x<<1
#define R x<<1|1
#define mid (l+r>>1)
#define lc L,l,mid
#define rc R,mid+1,r
#define Root 1,1,n
#define OK l>=Ll&&r<=Rr
#define rep(x,y,z) for(int x=(y);x<=(z);x++)
#define per(x,y,z) for(int x=(y);x>=(z);x--)
#define pb push_back
#define ull unsigned ll
#define e(x) for(int i=h[x],y=to[i];i;i=nxt[i],y=to[i])
#define E(x) for(auto y:p[x])
#define Pi pair<int,int>
#define ui unsigned int 
inline int read(){int s=0,w=1;char c=getchar();while(c<48||c>57) {if(c=='-') w=-1;c=getchar();}while(c>=48&&c<=57) s=(s<<1)+(s<<3)+c-48,c=getchar();return s*w;}
inline void pf(ll x){if(x<0) putchar('-'),x=-x;if(x>9)pf(x/10);putchar(x%10+48);}
const int N =3e4+5,M=4e6+5,inf=2147000000;
const ll llf=1e18;
using namespace std;
ll p;
int T,n,m;
ll dp[M],pr[M];
inline ll qp(ll a,ll b){
	if(!b)return 1;
	ll c=qp(a,b>>1);
	c=c*c%p;
	if(b&1)c=c*a%p;
	return c;
} 
int main(){
	freopen("pr.in","r",stdin);
	freopen("pr.out","w",stdout);
	p=read();
	T=read();
	while(T--){
		n=read(),m=read();
		int mx=n*m;
		dp[0]=pr[0]=1;
		rep(i,1,mx)pr[i]=1;
		rep(o,1,n){
			rep(i,1,mx){
				dp[i]=pr[i];
				if(i>m)dp[i]=(dp[i]-pr[i-m-1]+p)%p;
			}
			rep(i,1,mx)pr[i]=(pr[i-1]+dp[i])%p;
		}
		ll ans=0;
		rep(i,1,mx)(ans+=dp[i]*pr[i-1]%p)%=p;
		pf(ans*qp(qp(m+1,n*2),p-2)%p),putchar('\n');
	}
	return 0;
}
